package router

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	//配置跨域
	CheckOrigin: func(r *http.Request) bool {
	  return true
	},
}

//ws连接方法
func serveWebSocket(w http.ResponseWriter,r *http.Request){
	//将http升级成webscoket
	/*
		第一个参数是 http.ResponseWriter
		第二个参数是 http.Request
		第三个参数是 http.Header

		返回结果是 成功的ws实例和error
	*/
	conn,err := upgrader.Upgrade(w,r,nil)
	if err!=nil{
		fmt.Printf("创建失败，原因为%s",err.Error())
	}
	//结束时关闭ws连接
	defer conn.Close()

	//我们一般用死循环来保证一直连接
	for{
		//读取客户端发送的消息
		// func (c *websocket.Conn) ReadMessage() (messageType int, p []byte, err error)
		messageType,p,err := conn.ReadMessage()
		if err!=nil{
			fmt.Printf("读取客户端消息失败，原因为%s",err.Error())
		}

		//根据客户端消息进行处理
		err = conn.WriteMessage(messageType,p)
		if err!=nil{
			fmt.Printf("发送消息失败，原因为%s",err.Error())
		}

	}
}


func InitWebScoket(r *gin.Engine){
	r.GET("/ws",func (ctx *gin.Context){
		serveWebSocket(ctx.Writer,ctx.Request)
	})
}